var ud = require("./usesr_db.js")

// 获取用户的session_key
function getUserInfoSession() {  
  wx.login({
    success(res) {
      wx.setStorageSync("beva_login", res)
      console.log(res)
      if (res.code) {
        //发起网络请求
        wx.cloud.callFunction({
          name: 'getSession', //调用云函数获取session_key;
          data: {
            code: res.code,
          },
          success: res => {
            wx.hideLoading()
            // console.log(res.result.resultValue)
            var data = res.result.resultValue
            console.log(data)
            wx.setStorageSync("session_key", data) //吧小程序的session_ley 数据存储于缓存中
            console.log(data.session_key) //获取到了session_key的值；
            return res

          },
          fail: error => {
            console.log(error)
          }
        })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    }
  })
}
// 获取用户手机号
function getUserNumber(e) {
  console.log(e)

  let a = wx.getStorageSync("session_key") //获取存在缓存中的用户的session_key
  console.log(a)
  console.log("==============================================获取存在缓存中的用户的session_key")
  wx.cloud.callFunction({
    name: 'getWXnumber', //解析秘文，获得手机号码；
    data: {
      session_key: a.session_key,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    },
    success: res => {
      console.log(res)
      let data = {}
      data.tel = res.result.data.phoneNumber      
      data.unionid = a.unionid      
      ud.updateOpenidData(wx.getStorageSync("db_openid")[0]._id, data)
      

    },
    fail: err => {
      console.log(err)
    }

  })
}

module.exports = {
  getUserInfoSession_l: getUserInfoSession ,
  getUserNumber_l: getUserNumber
}